package top.archiesean.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import top.archiesean.pojo.Configuration;
import top.archiesean.pojo.MappedStatement;

import java.io.InputStream;
import java.util.List;

/**
 * @author ArchieSean
 * @create 2023/7/11
 */
public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析mapper.xml
     *
     * @param inputStream 字节输入流
     */
    public void parse(InputStream inputStream) {
        try {
            //解析mapper.xml
            Document document = new SAXReader().read(inputStream);
            //获取根标签 mapper标签
            Element rootElement = document.getRootElement();
            //获取查询
            List<Element> selects = rootElement.selectNodes("//select");
            //获取mapper的名称空间值
            String namespace = rootElement.attributeValue("namespace");
            selects.forEach(select -> {
                //获取id属性
                String id = select.attributeValue("id");
                //获取sql入参类型
                String paramterType = select.attributeValue("paramterType");
                //获取sql返回值类型
                String resultType = select.attributeValue("resultType");
                //获取sql语句
                String sqlText = select.getTextTrim();
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setResultType(resultType);
                mappedStatement.setParameterType(paramterType);
                mappedStatement.setSql(sqlText);
                String key = namespace + "." + id;
                configuration.getMappedStatementMap().put(key, mappedStatement);

            });
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }
}
